package com.yitong.Estshopping.controller;




import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.yitong.Estshopping.entity.Order;
import com.yitong.Estshopping.entity.Orderlog;
import com.yitong.Estshopping.entity.PayEntity;
import com.yitong.Estshopping.entity.Product;
import com.yitong.Estshopping.entity.User;
import com.yitong.Estshopping.entity.Walletlog;
import com.yitong.Estshopping.service.CategorySecondService;
import com.yitong.Estshopping.service.CategorysService;
import com.yitong.Estshopping.service.ImageService;
import com.yitong.Estshopping.service.OrderLogService;
import com.yitong.Estshopping.service.OrderService;
import com.yitong.Estshopping.service.PayInfoService;
import com.yitong.Estshopping.service.ProductService;
import com.yitong.Estshopping.service.UserService;
import com.yitong.Estshopping.service.WalletLogService;
import com.yitong.framework.Orderlogtext;
import com.yitong.framework.utils.Dingdan;
import com.yitong.framework.utils.MD5Util;

/**
 * 订单管理
 * @author YT
 *
 */

@Controller
public class OrderController{
	@Autowired
	private UserService userService;
	@Autowired
	private ProductService productService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderLogService orderlogservice;
	@Autowired
	private WalletLogService walletLogService;
	
	
	@Autowired
	private PayInfoService payInfoService;
	@Autowired
	private PayController payController;
	/**
	 * 订单生成
	 * @param session
	 * @param setid 生成订单
	 * @return
	 */
	@RequestMapping(value= "/getorder")
	public @ResponseBody Map<String, Object> getorder(HttpSession session,Integer setid,Integer num){
		Map<String,Object> map = new HashMap<String,Object>();
		User user = (User) session.getAttribute("user");
		if(user==null) {
			map.put("code", 0);
			map.put("msg", "请先登录");
			return map;
		}
		if(user.getQq()==null||user.getPhone()==null||user.getName()==null) {
			map.put("code", 3);
			map.put("msg", "请填写收件地址,联系方式");
			return map;
		}
		if(setid != null&& !user.getKey().equals(productService.getProduct(setid).getUser().getKey())) {
			//保存特定的数据,以免删除商品找不到订单
			Order order = new Order();
			Product product = productService.getProduct(setid);
			//订单号生成
			Dingdan dingdan=new Dingdan();
			String diof = dingdan.diof();
			order.setOif(diof);
			Date today = new Date();
			order.setOrdertime(today);
			//客户
			order.setCuser(user);
			//商家
			order.setUser(product.getUser());
			//商品id
			order.setPid(product.getPid());
			//商品名称
			order.setName(product.getPname());
			//商品图片
			String imgsrc = product.getImage().get(0).getSrc();
			order.setPimg(imgsrc);
			//收件人
			order.setUname(user.getName());
			//地址
			order.setAddr(user.getAddr());
			//电话
			order.setPhone(user.getPhone());
			//未付款
			order.setState(1);
			//总金额计算
			order.setTotal(num*product.getShopPrice());
			/**
			 * 数量*单价-优惠券
			 */
			//数量
			if(num==null)num=1;
			order.setNum(num);
			order.setPrice(product.getShopPrice());
			orderService.saveOrder(order);
			//日志记录
			Orderlog textlog = Orderlogtext.textlog(order.getCuser(),diof, order, 1);
			orderlogservice.seve(textlog );
			//数量减掉
			Integer nume=product.getInventory()-num;
			if(nume<0)nume=0;
			productService.updateProductInventory(product.getPid(), nume);;
			
			map.put("code", 2);
			map.put("msg", "订单生成成功,请支付......");
			//删除订单
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★开始★★★★★★");
			this.orderClose(diof);
			return map;
		}else {
			map.put("code", 1);
			map.put("msg", "你很皮,这可能是你自己的商品");
			return map;
		}
		
	}
	/**
	 * 查询订单
	 * @param session
	 * @return
	 */
	@RequestMapping("/userinfo/order")
    public String order(Model model, HttpSession session,@RequestParam(required=false) Integer state,@RequestParam(required=false) Integer page,@RequestParam(required=false) Integer limit) {
		User user = (User) session.getAttribute("user");
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		if(state==null) {
			state=1;
		}
		/**
		 * 查询订单
		 */
		List<Order> orderlist= orderService.listorder(user,state,page,limit);
		//查询订单数量
		Integer count1=orderService.count(user,1);
		Integer count2=orderService.count(user,2);
		Integer count3=orderService.count(user,3);
		Integer count4=orderService.count(user,4);
		Integer count10=orderService.count(user,10);
		session.setAttribute("orderlist", orderlist);
		session.setAttribute("page", page);
		session.setAttribute("limit", limit);
		session.setAttribute("state", state);
		session.setAttribute("count1", count1);
		session.setAttribute("count2", count2);
		session.setAttribute("count3", count3);
		session.setAttribute("count4", count4);
		session.setAttribute("count10", count10);
		/**
		 * 随机生成口令
		 * 防止支付失效
		 */
        return "user/order";
    }
	/**
	 * 修改订单收件地址
	 */
	@RequestMapping("/userinfo/editorder/{oif}")
    public @ResponseBody Map<String, Object> editorder(@PathVariable("oif") String oif,HttpSession session,String uname,String phone,String addr) {
		User user = (User) session.getAttribute("user");
		Map<String,Object> map = new HashMap<String,Object>();
		/**
		 * 根据订单号查询
		 */
		Order order=orderService.findOif(oif);
		/**
		 * 修改订
		 */
		
		order.setUname(uname);
		order.setPhone(phone);
		order.setAddr(addr);
		orderService.update(order);
		map.put("code", 0);
		Integer state = null;
		if (user.getUid()==order.getCuser().getUid()) {
			state=8;
		}else {
			state=7;
		}
		//日志记录
		Orderlog textlog = Orderlogtext.textlog(user,order.getOif(), order,state);
		orderlogservice.seve(textlog );
		return map;
	}
	/**
	 * 删除订单
	 */
	@RequestMapping("/userinfo/delorder/{oif}")
    public String delorder(@PathVariable("oif") String iof,HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer page=(Integer) session.getAttribute("page");
		if(page==null) {
			page=1;
		}
		Integer limit=(Integer) session.getAttribute("limit");;
		if(limit==null) {
			limit=12;
		}
		Integer state=(Integer) session.getAttribute("state");;
		if(state==null) {
			state=1;
		}
		/**
		 * 根据订单号查询
		 */
		Order order=orderService.findOif(iof);
		/**
		 * 状态小于3可以删除
		 */
		/**
		 * 1 可以取消订单
		 * 删除订单
		 */
		Integer states = null;
		System.out.println("订单状态"+order.getState());
		if(order.getState()==1) {
			states=5;
			Product product = productService.getProduct(order.getPid());
			Integer inventory = product.getInventory();
			Integer num = order.getNum();
			/**
			 * 退回数量
			 */
			productService.updateProductInventory(order.getPid(), inventory+num);
			//日志记录
			Orderlog textlog = Orderlogtext.textlog(user, order.getOif(), order,states);
			orderlogservice.seve(textlog );
			System.out.println(order);
			orderService.delete(order);
			/**
			 * 查询订单
			 */
			List<Order> orderlist= orderService.listorder(user,state,page,limit);
			session.setAttribute("orderlist", orderlist);
			session.setAttribute("page", page);
			session.setAttribute("limit", limit);
			session.setAttribute("state", state);
	        return "redirect:/userinfo/order";
		}else if(order.getState()==2 || order.getUser().getUid()==user.getUid()){
			states=6;
			Product product = productService.getProduct(order.getPid());
			Integer inventory = product.getInventory();
			Integer num = order.getNum();
			/**
			 * 退回数量
			 */
			productService.updateProductInventory(order.getPid(), inventory+num);
			/**
			 * 退款
			 */
			/**
			 * 支付宝支付订单退款
			 */
			PayEntity pEntity = payInfoService.getOut_trade_no(iof);
			if(pEntity!=null) {
				order.setState(10);
				orderService.update(order);
				return "redirect:/userinfo/alipayiof/"+iof;
			}else {
				
				/**
				 * 钱包支付订单退款
				 */
				Walletlog walletlog = new Walletlog(order.getTotal(),5, "TK"+order.getOif(), order.getOif(), JSON.toJSONString(order), new Date(), user);
				walletLogService.sevequxiao(walletlog);
				//日志记录
				Orderlog textlog = Orderlogtext.textlog(user, order.getOif(), order,states);
				orderlogservice.seve(textlog );
				System.out.println(order);
				orderService.delete(order);
				/**
				 * 查询订单
				 */
				List<Order> orderlist= orderService.listorder(user,state,page,limit);
				session.setAttribute("orderlist", orderlist);
				session.setAttribute("page", page);
				session.setAttribute("limit", limit);
				session.setAttribute("state", state);
				return "redirect:/userinfo/sell";
			}
			
		}else {
			return "/user/nobug";
		}
		
    }
	/**
	 * 支付宝订单处理
	 * @param iof
	 * @param session
	 * @return
	 */
	@RequestMapping("/userinfo/alipayiof/{oif}")
    public String alipayiof(@PathVariable("oif") String iof,HttpSession session) {
		return "/user/alipayiof";
	}
	
	/**
	 * 钱包支付
	 * @param oif
	 * @param session
	 * @return
	 */
	@RequestMapping("/userinfo/zhifuorder/{oif}")
    public @ResponseBody Map<String, Object> zhifuorder(@PathVariable("oif") String oif,HttpSession session){
		User user = (User) session.getAttribute("user");
		Map<String,Object> map = new HashMap<String,Object>();
		/**
		 * 根据订单号查询
		 */
		Order order=orderService.findOif(oif);
		if (user.getWallet()==null||walletLogService.usercount(user) < order.getTotal()) {
			map.put("code", 2);
			map.put("msg", "您的账户余额不足,请充值");
		}else {
			Walletlog walletlog = new Walletlog(order.getTotal(), 1, "ZF"+oif, oif, JSON.toJSONString(order), new Date(), user);
			walletLogService.seve(walletlog);
			order.setState(2);
			boolean flag = orderService.update(order);
			
			//日志记录
			Orderlog textlog = Orderlogtext.textlog(user, order.getOif(), order,2);
			orderlogservice.seve(textlog );
			if(flag) {
				map.put("code", 1);
				map.put("msg", "支付成功");
			}
		}
		return map;
	}
	
	/**
	 * 支付宝支付
	 * @throws IOException 
	 * @throws AlipayApiException 
	 */
	@RequestMapping("/userinfo/alipayzhifu/{oif}")
    public void alipayzhifu(@PathVariable("oif") String oif,HttpSession session,HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException{
		User user = (User) session.getAttribute("user");
		Map<String,Object> map = new HashMap<String,Object>();
		/**
		 * 根据订单号查询
		 */
		Order order=orderService.findOif(oif);
		
		PayEntity payEntity = new PayEntity();
		payEntity.setOut_trade_no(order.getOif());
		payEntity.setSubject(order.getName());
		payEntity.setUname(order.getCuser().getUserName());
		payEntity.setUid(order.getCuser().getUid().toString());;
		Float f = (float) (order.getTotal()*1.08);
		BigDecimal b = new BigDecimal(f);
		Float total = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		payEntity.setTotal_amount(total.toString());
		payEntity.setBody(order.getName()+" X " +order.getNum()+" 件 " +" 共计 "+total+"元");
		
		payController.playzhifu(request, response, null, null, null, null, null, null, payEntity);
		
	}
	/**
	 * 确认收货
	 */
	@RequestMapping("/userinfo/shouhuo/{oif}")
    public String shouhuo(@PathVariable("oif") String iof,HttpSession session) {
		User user = (User) session.getAttribute("user");
		/**
		 * 根据订单号查询
		 */
		Order order=orderService.findOif(iof);
		order.setState(4);
		//日志记录
		Orderlog textlog = Orderlogtext.textlog(user, order.getOif(), order,4);
		orderlogservice.seve(textlog );
		Walletlog walletlog = new Walletlog(order.getTotal(),2, "SH"+order.getOif(), order.getOif(), JSON.toJSONString(order), new Date(), order.getUser());
		walletLogService.seveShouhuo(walletlog);
		boolean flag = orderService.update(order);
		return "redirect:/userinfo/order?state=4#type=finishorder";
	}
	/**
	 * 订单关闭(设置指定20分钟后，删除订单)
	 * @param bolId
	 */
	public void orderClose(String oif) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
               // OrderService os= SpringContextUtils.getBean(OrderService.class);
                try {
                	System.out.println(oif);
            		Order order=orderService.findOif(oif);
            		System.out.println(order.toString());
            		/**
            		 * 状态小于3可以删除
            		 */
            		/**
            		 * 删除订单
            		 */
            		if(order.getState()<2) {
            			Integer states = null;
            			Product product = productService.getProduct(order.getPid());
            			Integer inventory = product.getInventory();
            			Integer num = order.getNum();
            			/**
            			 * 退回数量
            			 */
            			productService.updateProductInventory(order.getPid(), inventory+num);
            			//日志记录
            			Orderlog textlog = Orderlogtext.textlog(null, order.getOif(), order,10);
            			orderlogservice.seve(textlog );
            			System.out.println(order);
            			orderService.delete(order);
            			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★结束★★★★★★");
            		}
                    //Integer ret = os.updateState(bolId,0);
                    /*if(ret > 0) {
                        System.out.println("订单号："+bolId+"已关闭");
                    }*/
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 中断线程
                timer.cancel();
            }
        },30*60*1000);
    }
	
}
